Linear Search
Linear search is starting at the first element and examining them one by
one until the target element is found.
You could write linear search for a Vector (and it would be
a good exercise to do so); but there is a method that does this for you:
int indexOf(Object elem) // Search for the first occurrence of
// elem, testing for equality
// using the equals method of elem.
The method returns the index of the first occurrence of elem
or -1 if elem is not found.
Examine the following program. What will it print?
import java.util.* ;
class VectorEg
{
public static void main ( String[] args)
{
Vector names = new Vector( 10 );
names.addElement( "Amy" ); names.addElement( "Bob" );
names.addElement( "Chris" ); names.addElement( "Deb" );
names.addElement( "Chris" ); names.addElement( "Joe" );
System.out.println( names.indexOf( "Bob" ) );
System.out.println( names.indexOf( "Elaine" ) );
}
}